<template>
  <view class="certificate-container">
    <view class="certificate-list">
      <template v-for="(img, idx) in images">
        <!-- 前两张图片正常显示 -->
        <image
          v-if="idx < 2"
          :key="`img-normal-${idx}`"
          :src="img"
          mode="aspectFill"
          class="certificate-img"
        />
        <!-- 第三张图片和内容叠加显示（只有审核通过时才显示） -->
        <view v-else-if="idx === 2 && memberCardInfo.auditStatus === 1" :key="`img-special-${idx}`" class="certificate-img-wrapper">
          <image :src="img" mode="aspectFill" class="certificate-img" />
          <view class="certificate-special">
            <view class="left">
              <image :src="memberCardInfo.photo" mode="aspectFit" class="avatar-img"></image>
              <!-- 姓名 -->
              <view class="label name">{{ memberCardInfo.realName || '-' }}</view>
              <!-- 性别 -->
              <view class="label gender">{{ memberCardInfo.gender == 1 ? '男' : '女' }}</view>
              <!-- 民族 -->
              <view class="label nation">{{ memberCardInfo.nationality || '汉族' }}</view>
              <!-- 出生年月 -->
              <view class="label birth">{{ memberCardInfo.birthday || '-' }}</view>
              <!-- 工作单位 -->
              <view class="label work">{{ memberInfo.regUnit || '-' }}</view>
            </view>
            <view class="right">
              <!-- 会员编号 -->
              <view class="label member-id">{{ memberCardInfo.memberNo || '-' }}</view>
              <!-- 入会时间，仅保留年月日 -->
              <view class="label join-time">{{ formatYMD(memberInfo.createTime) }}</view>
              <!-- 所属红十字会 -->
              <view class="label organization"></view>
              <!-- 签发日期，仅保留年月日 -->
              <view class="label issue-date">{{ formatYMD(memberInfo.createTime) }}</view>
            </view>
          </view> 
        </view>
        <!-- 第三张图片（审核未通过或未审核时只显示图片） -->
        <image
          v-else-if="idx === 2 && memberCardInfo.auditStatus !== 1"
          :key="`img-simple-${idx}`"
          :src="img"
          mode="aspectFill"
          class="certificate-img"
        />
        <!-- 第四张图片和缴费记录叠加显示（只有审核通过时才显示） -->
        <view v-else-if="idx === 3 && memberCardInfo.auditStatus === 1" :key="`img-payment-${idx}`" class="certificate-img-wrapper">
          <image :src="img" mode="aspectFill" class="certificate-img" />
          <view class="payment-records">
            <!-- 左侧列表 -->
            <view class="payment-list payment-left">
              <view 
                v-for="(record, recordIdx) in paymentRecords.filter(r => r.side === 'left')" 
                :key="recordIdx" 
                class="payment-item"
              >
                <view class="payment-number">{{ record.number }}</view>
                <view class="payment-date">{{ record.date }}</view>
                <view class="payment-amount">{{ record.amount }}</view>
                <view class="payment-receiver">{{ record.receiver }}</view>
              </view>
            </view>
            <!-- 右侧列表 -->
            <view class="payment-list payment-right">
              <view 
                v-for="(record, recordIdx) in paymentRecords.filter(r => r.side === 'right')" 
                :key="recordIdx" 
                class="payment-item"
              >
                <view class="payment-number">{{ record.number }}</view>
                <view class="payment-date">{{ record.date }}</view>
                <view class="payment-amount">{{ record.amount }}</view>
                <view class="payment-receiver">{{ record.receiver }}</view>
              </view>
            </view>
          </view>
        </view>
        <!-- 第四张图片（审核未通过或未审核时只显示图片） -->
        <image
          v-else-if="idx === 3 && memberCardInfo.auditStatus !== 1"
          :key="`img-simple-${idx}`"
          :src="img"
          mode="aspectFill"
          class="certificate-img"
        />
        <!-- 其他图片正常显示 -->
        <image
          v-else
          :key="`img-other-${idx}`"
          :src="img"
          mode="aspectFill"
          class="certificate-img"
        />
      </template>
    </view>
    <!-- 申请修改按钮 -->
    <view class="footer-btn">
      <view class="primary-btn" @click="handleApplyModify">{{ buttonText }}</view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getMemberInfo, getOrderList, getMemberCard } from '@/utils/api.js'

// const images = [
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/f3ccdd27d2000e3f9255a7e3e2c48800.jpg',
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/156005c5baf40ff51a327f1c34f2975b.jpg',
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/799bad5a3b514f096e69bbc4a7896cd9.jpg',
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/d0096ec6c83575373e3a21d129ff8fef.jpg',
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/032b2cc936860b03048302d991c3498f.jpg',
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/18e2999891374a475d0687ca9f989d83.jpg',
//     'https://puqinzc.oss-cn-beijing.aliyuncs.com/fe5df232cafa4c4e0f1a0294418e5660.jpg'
// ]

const images = [
	'https://puqinzc.oss-cn-beijing.aliyuncs.com/1ad8ba55ab5f47539ac4d7ea5766e9ed.png',
	'https://puqinzc.oss-cn-beijing.aliyuncs.com/e555cce7531741a792d4937e370244fd.png',
	'https://puqinzc.oss-cn-beijing.aliyuncs.com/522a8290974e44159d37df2930f8aad7.png',
	'https://puqinzc.oss-cn-beijing.aliyuncs.com/0f410c28864941f49dcad6ec962884e1.png',
	'https://puqinzc.oss-cn-beijing.aliyuncs.com/199c020856fe491b9429afb94491c10a.png',
	'https://puqinzc.oss-cn-beijing.aliyuncs.com/c5ed5e4feec04dc49f512a15f3facaa6.png'
]

// 会员信息
const memberInfo = ref({})

// 会员卡片信息（从 getMemberCard 获取）
const memberCardInfo = ref({})

// 缴费记录数据
const paymentRecords = ref([])

// 按钮文字（根据审核状态显示）
const buttonText = computed(() => {
  if (memberCardInfo.value.auditStatus == 0) return '审核中'
  if (!memberCardInfo.value.auditStatus) return '申请修改'
  if (memberCardInfo.value.auditStatus == 1) return '申请修改'
  if (memberCardInfo.value.auditStatus == 2) return '重新申请'
  return '申请修改'
})

// 获取会员信息
const fetchMemberInfo = async () => {
  try {
    const response = await getMemberInfo()
    if (response.code === 0 && response.data) {
      memberInfo.value = response.data
      // 获取会员信息后，再调用 getMemberCard 和 fetchPaymentRecords
      if (response.data.id) {
        // 并行获取会员卡片信息和缴费记录
        await Promise.all([
          fetchMemberCard(response.data.id),
          fetchPaymentRecords(response.data.id)
        ])
      }
    }
  } catch (error) {
    console.error('获取会员信息失败:', error)
    uni.showToast({
      title: '获取会员信息失败',
      icon: 'none'
    })
  }
}

// 获取会员卡片信息
const fetchMemberCard = async (memberId) => {
  try {
    const response = await getMemberCard(memberId)
    if (response.code === 0 && response.data) {
      memberCardInfo.value = response.data
    } else {
      console.error('获取会员卡片信息失败:', response.msg)
    }
  } catch (error) {
    console.error('获取会员卡片信息失败:', error)
  }
}

// 获取缴费记录
const fetchPaymentRecords = async (userId) => {
  try {
    if (!userId) {
      // 如果未传入 userId，尝试从 memberInfo 或缓存获取
      if (memberInfo.value?.id) {
        userId = memberInfo.value.id
      } else {
        const userInfo = uni.getStorageSync('user_info') || {}
        userId = userInfo.id
      }
    }
    
    if (!userId) {
      console.warn('用户信息获取失败，无法获取缴费记录')
      return
    }
    
    const response = await getOrderList({
      userId: userId,
      page: 1,
      size: 50 // 获取更多记录用于展示
    })
    
    if (response.code === 0 && response.data && response.data.records) {
      const records = response.data.records.map((item, index) => ({
        number: String(index + 1), 
        date: formatYMD(item.createTime),
        amount: item.amount ? item.amount.toFixed(2) : '0.00',
        receiver: '枣庄市红十字会',
        side: index < 13 ? 'left' : 'right' // 前13条显示在左侧，后面的显示在右侧
      }))
      
      paymentRecords.value = records
    }
  } catch (error) {
    console.error('获取缴费记录失败:', error)
    uni.showToast({
      title: '获取缴费记录失败',
      icon: 'none'
    })
  }
}

// 页面显示时获取会员信息和缴费记录
onShow(() => {
  fetchMemberInfo()
})

// 仅保留年月日
const formatYMD = (val) => {
  if (!val) return '-'
  try {
    // 支持传入 "YYYY-MM-DD HH:mm:ss" 或时间戳或 ISO 字符串
    const d = typeof val === 'number' ? new Date(val) : new Date(String(val).replace(/-/g, '/'))
    if (isNaN(d.getTime())) return '-'
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
  } catch (e) {
    return '-'
  }
}

// 处理申请修改点击
const handleApplyModify = () => {
  // 检查会员信息是否存在
  if (!memberInfo.value?.id) {
    uni.showToast({
      title: '会员信息获取失败',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: `/pages/my/editCertificate?id=${memberInfo.value.id}`
  })
}
</script>

<style lang="scss" scoped>
.certificate-container {
  min-height: 100vh;
  background: #f8f9fb;
  padding: 32rpx 0;
  padding-bottom: 140rpx; /* 为固定底部按钮留出空间 */
}

.certificate-list {
  width: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
}

.certificate-img {
  width: 750rpx;
  height: 525rpx !important;
  border-radius: 16rpx;
  display: block;
  object-fit: cover;
}

.certificate-img-wrapper {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.certificate-special {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 0 40rpx;
  box-sizing: border-box;
  pointer-events: none;

  .left {
    position: relative;
    padding-top: 235rpx;
    padding-left: 100rpx;
    flex: 1;
    overflow: hidden;
    
    .avatar-img {
      width: 84rpx;
      height: 130rpx;
      position: absolute;
      top: 62rpx;
      left: 106rpx;
      border-radius: 8rpx;
      object-fit: cover;
    }

    .label {
      font-size: 20rpx;
      color: #333;
      line-height: 1.8;
      margin-bottom: 16rpx;
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 200rpx;
    }
  }
  
  .right {
    flex: 1;
    padding-top: 94rpx;
    padding-left: 160rpx;
    
    .label {
      font-size: 18rpx;
      color: #333;
      line-height: 1.4;
      margin-bottom: 16rpx;
      font-weight: 500;
      max-width: 200rpx;
      
      &.join-time{
        padding-top: 108rpx;
      }

      &.organization{
        padding-top: 50rpx;
      }

      &.issue-date{
        padding-top: 46rpx;
      }
    }
  }
}

.special-content {
  width: 90%;
  border-radius: 16rpx;
  padding: 24rpx 12rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.special-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #d32f2f;
  text-align: center;
  margin-bottom: 12rpx;
}

.special-info-row {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 4rpx;
}

.special-info-blank {
  flex: 1;
  border-bottom: 2rpx solid #ccc;
  margin: 0 8rpx;
  min-width: 80rpx;
  height: 32rpx;
}

/* 缴费记录样式 */
.payment-records { 
  position: absolute;
  top: 100rpx;
  left: 40rpx;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.payment-list {
  position: absolute;
  width: 50%;
  height: 100%;
  
  &.payment-left {
    left: 0;
  }
  
  &.payment-right {
    left: 50%;
  }
}

.payment-item {
  width: 300rpx;
  height: 28rpx;
  margin-bottom: 4rpx;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  
  .payment-number {
    width: 30rpx;
    font-size: 16rpx;
    color: #333;
    text-align: center;
    font-weight: 500;
  }
  
  .payment-date {
    width: 100rpx;
    font-size: 16rpx;
    color: #333;
    text-align: center;
    font-weight: 500;
  }
  
  .payment-amount {
    width: 70rpx;
    font-size: 16rpx;
    color: #333;
    text-align: center;
    font-weight: 500;
  }
  
  .payment-receiver {
    width: 120rpx;
    font-size: 16rpx;
    color: #333;
    text-align: center;
    font-weight: 500;
  }
}

.footer-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: calc(100% - 48rpx);
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 24rpx 28rpx 24rpx;
  z-index: 100;

  .primary-btn {
    &:active {
      transform: scale(0.98);
    }
  }
}
</style>
